package ua.mykola.util;

import static java.lang.Math.max;
import static java.lang.Math.min;

public class MathUtil
{

    /**
     * Uses Euclidean algorithm
     */
    public int gcd(int m, int n)
    {
        if (m == n)
            return m;
        else
        {
            return gcd(max(m, n) - min(m, n), min(m, n));
        }
    }

    public int lcm(int m, int n)
    {
        // m*n=gcd(m,n)*lcm(m,n)
        return m * (n / gcd(m, n));
    }

    public double pow(int x, int y)
    {
        double res = 1;
        long tmp = x;
        int copyY = Math.abs(y);
        double beforeOverflow;
        for (int i = 0; i < 32; copyY >>= 1, i++)
        {
            beforeOverflow = Double.MAX_VALUE / tmp;
            if ((copyY & 1) == 1)
            {
                if (res < beforeOverflow)
                {
                    res *= tmp;
                }
                else
                {
                    throw new RuntimeException(String.format("%d^%d can not fit into double", x, y));
                }
            }
            tmp *= tmp;
        }

        if (y < 0)
            res = 1 / res;
        return res;
    }
}
